package com.dragon.modules.yuegou.service.impl.merchant;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.modules.yuegou.entity.merchant.MerchantShortUrlEntity;
import com.dragon.modules.yuegou.mapper.merchant.MerchantShortUrlMapper;
import com.dragon.modules.yuegou.model.merchant.MerchantShortUrl;
import com.dragon.modules.yuegou.properties.MerchantProperties;
import com.dragon.modules.yuegou.service.merchant.MerchantShortUrlService;
import com.dragon.modules.yuegou.utils.NumberUtils;
import com.dragon.modules.yuegou.web.Check;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * 商户短码表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-09-29 10:10:16
 * @version 2.0
 */
@Service("merMerchantShortUrlService")
public class MerchantShortUrlServiceImpl
		extends ServiceImpl<MerchantShortUrlMapper, MerchantShortUrlEntity>
		implements MerchantShortUrlService {

	@Autowired
	private MerchantProperties merchantProperties;

	private Random random = new Random();

	@Override
	public String getMerchantIdByCode(String base62) {
		Check.notNull(base62, "编码不能为空");
		if (StringUtils.isEmpty(base62)) {
			return "";
		}
		Long code = NumberUtils.base62ToDecimal(base62.substring(1));
		MerchantShortUrlEntity merchantShortUrl = getById(String.valueOf(code));
		return merchantShortUrl.getMerchantId();
	}

	@Override
	public String getQRCodeShortUrl(String merchantId) {
		Check.notNull(merchantId, "商户id不能为空");

		// 生成短链接保存到数据库和缓存
		MerchantShortUrl merchantShortUrl = new MerchantShortUrl();
		merchantShortUrl.setMerchantId(merchantId);

		int num = baseMapper.getGeneratedShortUrlKey(merchantShortUrl);
		if (num == 1) {
			// 生成base62 码
			String shortCode = NumberUtils.decimal2base62(Long.valueOf(merchantShortUrl.getId()));
			int r = this.random.nextInt(62);
			String randCode = NumberUtils.decimal2base62(r);
			String newShortCode = randCode + shortCode;
			String shortUrl = assembleShortUrl(newShortCode);
			merchantShortUrl.setShortCode(newShortCode);
			merchantShortUrl.setMerchantId(merchantId);
			merchantShortUrl.setShortUrl(shortUrl);
			// 更新数据库
			updateById(merchantShortUrl);
			return shortUrl;
		}
		return null;
	}

	private String assembleShortUrl(String base62) {
		return merchantProperties.getDomain().endsWith("/") ? merchantProperties.getDomain() + base62
				: merchantProperties.getDomain() + "/" + base62;
	}
}